<?php

// +----------------------------------------------------------------------
// | Admin Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-admin
// | github 代码仓库：https://github.com/zoujingli/think-plugs-admin
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\paths\controller;

use app\common\model\admin\AccountModel;
use app\common\model\paths\ClassModel;
use app\common\model\paths\UserClassModel;
use app\common\model\index\UserModel;
use app\common\service\CrmebService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemUser;

/**
 * 用户申请
 * @class Base
 * @package app\admin\controller
 */
class ClassApply extends Controller
{
    /**
     * 用户申请
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index ()
    {
        $this->type = $this->request->get('type', 'all');

        UserClassModel::mQuery()->layTable(function () {
            $this->title = '申请班级';
            $this->type_arr = ['all'=>lang('全部'),'apply'=>lang('申请中'), 'agree'=>lang('已同意'),'refuse'=>lang('已拒绝'),];
            $this->teacher_arr = SystemUser::mk()->where('account_id', $this->account_id)->where('usertype', 'teacher')->where('is_deleted' , 0)->column('nickname', 'id');

        }, function (QueryHelper $query) {

            if ($this->type == 'apply') {
                $query->where('status', UserClassModel::STATUS_APPLY);
            }
            if ($this->type == 'agree') {
                $query->where('status', UserClassModel::STATUS_AGREE);
            }

            if ($this->type == 'refuse') {
                $query->where('status', UserClassModel::STATUS_REFUSE);
            }
            $query->order('id', 'desc');
            // 数据列表搜索过滤
            $query->like('name')->equal('user_id,status,platform_id')->dateBetween('create_at');
        });
    }

    protected function _index_page_filter (&$data)
    {

        $index_userids = $class_ids = $teacher_ids =[];
        array_map(function ($item) use (&$teacher_ids, &$index_userids, &$class_ids) {

            $index_userids[] = $item['index_user_id'];
            $class_ids[]     = $item['class_id'];
            $teacher_ids[]   = $item['user_id'];

        }, $data);

        $platform_arr    = AccountModel::mk()->where("1=1")->column('title', 'id');
        $teacher_arr     = SystemUser::mk()->whereIn("id", array_unique($teacher_ids))->column('nickname', 'id');
        $class_arr       = ClassModel::mk()->whereIn("id", array_unique($class_ids))->column('name', 'id');

        // 学历
        $background = UserModel::getBackgroundArr();

        UserModel::mk()->whereIn("id", array_unique($index_userids))->select()->each(function ($item)  use (&$index_user_arr, $platform_arr, $background) {

            $job_place = $platform_arr[$item['job_place']] ?? '-';

            $item['true_name'] = $item['true_name']."(". ($item['job_number'] ? $item['job_number'] : '-') .")";
            $item['college']   = $job_place .'-'. $item['job_depart'] .'-'. $item['major'];
            $item['edu_background'] = $background[ $item['edu_background']];

            $index_user_arr[$item['id']] = $item;
        });


        foreach ($data as &$item) {

            $item['platform_name']   = $platform_arr[$item['platform_id']] ?? '';
            $item['user_name']       = $teacher_arr[$item['user_id']] ?? '';
            $item['index_user_name'] = $index_userids[$item['index_user_id']] ?? '';
            $item['class_name']      = $class_arr[$item['class_id']] ?? '';


            $item['index_user_name'] = $index_user_arr[$item['index_user_id']] ? $index_user_arr[$item['index_user_id']]['true_name'] :'';

            $item['index_user_background'] = $index_user_arr[$item['index_user_id']] ? $index_user_arr[$item['index_user_id']]['edu_background'] :'';
            $item['index_user_college'] = $index_user_arr[$item['index_user_id']] ? $index_user_arr[$item['index_user_id']]['college'] :'';
            $item['index_user_background'] = $index_user_arr[$item['index_user_id']] ? $index_user_arr[$item['index_user_id']]['edu_background'] :'';

        }
    }

    /**
     * 同意
     *
     *
     * @return void
     */
    public function agree ()
    {
        $id = $this->request->post('id');

        $userClassObj = UserClassModel::mk()->where('id', $id)->find();

        $userClassObj->status =  UserClassModel::STATUS_AGREE;
        $userClassObj->check_at = date('Y-m-d H:i:s');
        $userClassObj->save();

        ClassModel::mk()->where('id', $userClassObj->class_id)->inc('apply_num')->update();

        // 注册商城用户
        $this->_registerCrmebUser($userClassObj->index_user_id);

        $this->success('成功');
    }

    /**
     * 拒绝
     *
     *
     * @return void
     */
    public function refuse ()
    {

        $this->status = UserClassModel::STATUS_REFUSE;
        UserClassModel::mForm();

        /*$id = $this->request->post('id');

        if ($this->request->isGet()) {

        }

        UserClassModel::mk()->where('id', $id)->update(['status' => UserClassModel::STATUS_AGREE]);

        $this->success('成功');*/
    }

    /**
     * _registerCrmebUser
     *
     * @Description 注册商城用户
     * @author wangqinghui
     * @date 2024-10-14 16:58
     * @param integer $user_id
     * @return void
     */
    protected function _registerCrmebUser(int $user_id = 0)
    {
        // 获取用户信息
        if(empty($user_id) || ($user_id <= 0)){
            $this->error('用户不存在');
        }
        $field = 'id,account,password_plaintext,mobile,email,true_name,is_crmeb_user,is_deleted';
        $userInfo = UserModel::mk()->field($field)->where('id', $user_id)->find();
        if(empty($userInfo) || ($userInfo['is_deleted'] == 1)){
            $this->error('用户不存在');
        }
        if(empty($userInfo['is_crmeb_user'])){
            // 未注册过商城用户才注册
            $crmebService = CrmebService::getInstance();
            $res = $crmebService->setConfig()->getToken()->addUser($userInfo->toArray());
            if(empty($res['code']) || ($res['code'] != 1)){
                $this->error($crmebService->getError());
            }
            UserModel::mk()->where('id', $user_id)->update(['is_crmeb_user' => 1]);
        }
    }
}